//
//  AppDelegate.swift
//  newShaohuoRen
//
//  Created by hujinbiao on 2018/3/21.
//  Copyright © 2018年 hujinbiao. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift
import SwiftProgressHUD
import SlideMenuControllerSwift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,JPUSHRegisterDelegate,WXApiDelegate {
    
    var window: UIWindow?
    
    var manager : RecordManager?
    
    fileprivate func createMenuView() {
        
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let mainNav: UINavigationController = UINavigationController(rootViewController: SHHomeViewController())
        UINavigationBar.appearance().tintColor = UIColor(hexString: "434343")
        let leftVc = SHDrawerViewController()
        leftVc.navController = mainNav
        let slideMenuController = SlideMenuController(mainViewController: mainNav, leftMenuViewController: leftVc)
        self.window?.backgroundColor = UIColor(red: 236.0, green: 238.0, blue: 241.0, alpha: 1.0)
        self.window?.rootViewController = slideMenuController
        self.window?.makeKeyAndVisible()
    }
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        IQKeyboardManager.sharedManager().enable = true
        //控制点击背景是否收起键盘
        IQKeyboardManager.sharedManager().shouldResignOnTouchOutside = true
        //控制键盘上的工具条文字颜色是否用户自定义
        IQKeyboardManager.sharedManager().shouldToolbarUsesTextFieldTintColor = true
        //将右边Done改成完成
        IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemText = "完成"
        // 控制是否显示键盘上的工具条
        IQKeyboardManager.sharedManager().enableAutoToolbar = true
        //最新版的设置键盘的returnKey的关键字 ,可以点击键盘上的next键，自动跳转到下一个输入框，最后一个输入框点击完成，自动收起键盘
        IQKeyboardManager.sharedManager().toolbarManageBehaviour = .byPosition
        
        //设置主界面
        createMenuView()
        
       //极光推送
        let entity = JPUSHRegisterEntity()
        entity.types = Int(JPAuthorizationOptions.alert.rawValue) | Int(JPAuthorizationOptions.badge.rawValue) | Int(JPAuthorizationOptions.sound.rawValue)
        JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
        JPUSHService.setup(withOption: launchOptions, appKey: "b3b66a730eecb175e8815b57", channel: "App Store", apsForProduction: isProduction)
        
        //微信
        WXApi.registerApp("wxf667c0b2c97be8e5")
        
        return true
    }
    
    func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
        
        return WXApi.handleOpen(url, delegate: self)
    }
    
    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        
        if url.host == "safepay" {
            AlipaySDK.defaultService().processOrder(withPaymentResult: url, standbyCallback: { (resultDic) in
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "alipayResult"), object: resultDic)
            })
        }else {
            WXApi.handleOpen(url, delegate: self)
        }
        
        return true
    }
    
    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        
        if url.host == "safepay" {
            AlipaySDK.defaultService().processOrder(withPaymentResult: url, standbyCallback: { (resultDic) in
                if let Alipayjson = resultDic as NSDictionary? {
                    let resultStatus = Alipayjson.value(forKey: "resultStatus") as! String
                    if resultStatus == "9000"{
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "alipayResult"), object: nil)
                    }
                }
            })
        }else {
            WXApi.handleOpen(url, delegate: self)
        }
        
        return true
    }
    
    func onReq(_ req: BaseReq!) {
        
        print(req.type)
    }
    
    func onResp(_ resp: BaseResp!) {
        if resp.isKind(of: SendAuthResp.self) {
            let authResp = resp as! SendAuthResp
            if authResp.errCode == 0 {
                let notificationName = Notification.Name(rawValue: "weixinAuthorizationSuccess")
                NotificationCenter.default.post(name: notificationName, object:authResp.code)
            }else {
                SwiftProgressHUD.showOnlyText("登录失败")
            }
        }else if resp .isKind(of: PayResp.self) {
            if resp.errCode == 0 {
                let notificationName = Notification.Name(rawValue: "weixinpayResult")
                NotificationCenter.default.post(name: notificationName, object:resp.errCode)
            }else {
                SwiftProgressHUD.showOnlyText("支付失败")
            }
        }
        
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        JPUSHService.registerDeviceToken(deviceToken)

    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("极光推送失败\(error)")
    }

    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {

        if UserNotificationSettingModel.sharedInstance.is_voice_off! {
            let fileStr = Bundle.main.path(forResource: UserNotificationSettingModel.sharedInstance.is_voice_sex!, ofType: ".caf")
            manager = RecordManager()
            manager?.play(filePath: fileStr!)
        }
        let userInfo = notification.request.content.userInfo
        if (notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))!{
            JPUSHService.handleRemoteNotification(userInfo)
        }
        completionHandler(Int(UNNotificationPresentationOptions.alert.rawValue))
    }

    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
        
        if UserNotificationSettingModel.sharedInstance.is_voice_off! {
            let fileStr = Bundle.main.path(forResource: UserNotificationSettingModel.sharedInstance.is_voice_sex!, ofType: ".caf")
            manager = RecordManager()
            manager?.play(filePath: fileStr!)
        }
        let userInfo = response.notification.request.content.userInfo
        if (response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))! {
            JPUSHService.handleRemoteNotification(userInfo)
        }
        completionHandler()
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        JPUSHService.handleRemoteNotification(userInfo)
        completionHandler(.newData)
    
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
        JPUSHService.handleRemoteNotification(userInfo)
    }
    
    func applicationWillEnterForeground(_ application: UIApplication) {
        application.applicationIconBadgeNumber = 0
        application.cancelAllLocalNotifications()
    }
    
    func applicationDidEnterBackground(_ application: UIApplication) {
        application.applicationIconBadgeNumber = 0
    }

}

